import { createSlice, PayloadAction } from '@reduxjs/toolkit'
// import { AppThunk } from '../index's

// state变量类型
type Item = {
  id: number
  name: string
}
export type Query = {
  total_count: number,
  page: number,
  per_page: number
}
type Cover = {
  type: number
  images: string[]
}
export type ArticleList = {
  comment_count: number
  cover: Cover
  id: string
  like_count: number
  pubdate: string
  read_count: number
  status: number
  title: string
}
interface ArticleType {
  total_count: number,
  page: number,
  per_page: number
  results: ArticleList[]
}
export interface articleState {
  channelList: Array<Item>
  query: Query
  articleList: ArticleList[]
}
export const article = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'article',
  // 1. 定义变量(状态数据)
  initialState: {
    channelList: [],
    articleList: [],
    query: {
      total_count: 0,
      page: 1,
      per_page: 10
    }
  } as articleState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    getChannelsList(state, action: PayloadAction<Item[]>) {
      if (!action.payload) return
      state.channelList = action.payload
    },
    getArticleList(state, action: PayloadAction<ArticleType>) {
      if (!action.payload) return
      const { results, ...rest } = action.payload
      state.query = rest
      state.articleList = results
    }
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { getChannelsList, getArticleList } = article.actions


// 导出reducer(创建store使用)
export default article.reducer